import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
import store from '@/store'
import { ElMessage } from 'element-plus'

// 路由规则
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login')
  },
  {
    path: '/testvuex',
    name: 'TestVuex',
    component: () => import('../views/Vuex的使用.vue')
  },
  {
    path: '/member/checkout',
    name: 'Checkout',
    component: () => import('../views/member/checkout.vue')
  },
  {
    path: '/member/pay',
    name: 'Pay',
    component: () => import('../views/member/pay/index.vue')
  },
  {
    path: '/pay/callback',
    name: 'PayResult',
    component: () => import('../views/member/payResult/index.vue')
  }
]

// 创建路由实例
const router = createRouter({
  // 使用hash方式实现路由
  history: createWebHashHistory(),
  // 配置路由规则
  routes,

  // 每次路由跳转触发此函数
  scrollBehavior() {
    // return 期望页面滚动到哪个的位置
    return {
      top: 0,
      left: 0
    }
  }
})

// 权限路由路径
const authList = [
  '/member/order',
  '/member/checkout',
  '/member/pay',
  '/pay/callback'
]

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 已登录
  if (token) {
    if (to.path === '/login') {
      // 不能再访问登录页
      ElMessage.error('您已登录，不能再访问')
      next('/')
    } else {
      // 可以访问其他页面
      next()
    }
  } else {
    // 未登录
    if (authList.includes(to.path)) {
      // 访问的是权限路径
      ElMessage.error('请先登录，再访问')
      next(`/login?redirect=${to.path}`)
    } else {
      // 非权限路径
      next()
    }
  }
})

export default router
